package servlet;

import com.sun.org.apache.bcel.internal.generic.Select;
import dao.BillDao;
import dao.CardDao;
import dao.ManagerDao;
import dao.StudentDao;
import pojo.Bill;
import pojo.Card;
import pojo.Manager;
import pojo.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author konley
 * @date 2020-06-11 22:04
 */
@WebServlet("/ManagerServlet")
public class ManagerServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String m = request.getParameter("m");
        System.out.println("ManagerServlet m = " + m);
        if (m.equals("searchSid") || m.equals("searchName")) {  //简单查学生
            searchStu(request, response, m);
        } else if (m.equals("searchStuAll")) {   //查某个学生所有信息
            searchStudentAll(request, response);
        } else if (m.equals("doUpdate")) { //跳转到更新页
            doUpdate(request, response);
        } else if (m.equals("update")) { //执行更新
            update(request, response);
        } else if(m.equals("searchCid")){   //查饭卡
            searchStudentAllByCid(request,response);
        } else if(m.equals("toAdd")){   //跳转到开卡页
            toAdd(request,response);
        } else if(m.equals("add")){ //添加学生、开卡、生产账单
            add(request,response);
        } else if(m.equals("toAddCardMoney")){  //准备饭卡充值，跳转到饭卡页
            toAddCardMoney(request,response);
        } else if(m.equals("addCardMoney")){    //执行饭卡充值
            addCardMoney(request,response);
        }else if(m.equals("delete")){   //删除学生
            delete(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    //简单查学生列表
    public void searchStu(HttpServletRequest request, HttpServletResponse response, String m) throws ServletException, IOException {
        String msg = null;
        String txt = request.getParameter("txt");
        List<Student> list = null;
        if (txt.equals("")) { //没有输入，查所有 ==> 模糊查名字
            list = new StudentDao().getByName("");
        } else {
            if (m.equals("searchSid")) {  //根据学号查
                Student stu = null;
                try {   //非法输入：NumberFormatException用户输入字符串
                    stu = new StudentDao().getById(Integer.parseInt(txt));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    msg = " 【请输入纯数字】，";
                }
                if (stu != null) { // 找到了
                    list = new ArrayList<Student>();
                    list.add(stu);
                } else { //找不到
                    if (txt.length() != 5) {   //非法输入：位数不等于5
                        if (msg == null) {  //避免上面没抛出异常，msg=null的情况
                            msg = "";
                        }
                        msg += "【请输入五位数】，";
                    }
                    if (msg == null) {  //避免msg=null的情况
                        msg = "";
                    }
                    msg += "找不到该学生，请重新输入学号后再试！";
                }
            } else { //根据姓名查
                list = new StudentDao().getByName(txt);
                if (list == null) { //找不到
                    msg = "找不到该学生，请重新输入姓名后再试！";
                }
            }
        }
        request.setAttribute("list", list);
        request.setAttribute("stuMsg", msg);
        request.getRequestDispatcher("/managerView.jsp").forward(request, response);
    }

    //查询单个学生的所有信息
    public void searchStudentAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int sid = Integer.parseInt(request.getParameter("sid"));
        String msg = null;
        msg = request.getAttribute("msg")+"";//开卡成功的消息
        //查学生信息、学生卡信息、学生消费记录
        Student student = new StudentDao().getById(sid);
        Card card = new CardDao().getCard(sid);
        List<Bill> bills = new BillDao().getBillsBySid(sid);
        //存入请求并转发到管理员管理学生详情页
        request.setAttribute("msg",msg);
        request.setAttribute("student", student);
        request.setAttribute("card", card);
        request.setAttribute("bills", bills);
        request.getRequestDispatcher("/studentViewByManager.jsp").forward(request, response);
    }

    //请求修改学生，跳转到修改学生页
    public void doUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Student student = new StudentDao().getById(Integer.parseInt(id));
        request.setAttribute("student", student);
        request.getRequestDispatcher("/studentUpdateByManager.jsp").forward(request, response);
    }

    //执行修改学生，跳回管理学生页
    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg = "更新成功！";
        Student stu = new Student();
        int sid = Integer.parseInt(request.getParameter("sid"));
        stu.setSid(sid);
        stu.setName(request.getParameter("name"));
        stu.setPassword(request.getParameter("password"));
        stu.setSex(request.getParameter("sex"));
        stu.setDept(request.getParameter("dept"));
        stu.setTel(request.getParameter("tel"));
        boolean rs = new StudentDao().studentUpdate(stu);
        if (!rs) {
            msg = "更新失败！";
        }
       //使用查询单个学生信息的方法来执行跳转
        request.setAttribute("msg",msg);
        searchStudentAll(request,response);
    }
    //根据cid查询单个学生的所有信息
    public void searchStudentAllByCid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg = null;
        Card card = null;
        try {   //非法输入：NumberFormatException用户输入字符串
            int cid = Integer.parseInt(request.getParameter("cid"));
            System.out.println("cid = " + cid);
            card = new CardDao().getCardByCid(cid);
        } catch (NumberFormatException e) {
            msg = "【请输入纯数字】，";
            if(request.getParameter("cid")=="")
                msg="【请不要留空】，";
            //如果有非法输入，指定card为null，不让跳转
            card=null;
        }
        //查学生信息、学生卡信息、学生消费记录
        if(card != null){   //找到了
            int sid =card.getSid();
            Student student = new StudentDao().getById(sid);
            List<Bill> bills = new BillDao().getBillsBySid(sid);
            //存入请求并转发到管理员管理学生详情页
            request.setAttribute("student", student);
            request.setAttribute("card", card);
            request.setAttribute("bills", bills);
            request.setAttribute("msg",null);
            request.getRequestDispatcher("/studentViewByManager.jsp").forward(request, response);
        }else{  //找不到
            if(msg==null){  //表示用户没有非法输入
                msg = "";
            }
            msg += "找不到该饭卡，请检查后再试";
            request.setAttribute("cardMsg",msg);
            request.getRequestDispatcher("/managerView.jsp").forward(request, response);
        }
    }

    //准备开卡
    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取mid和manger对象，做二次验证
        int mid = Integer.parseInt(request.getParameter("mid"));
        Manager manger = new ManagerDao().getManager(mid);
        request.setAttribute("manager",manger);
        request.getRequestDispatcher("/addStudentAndCard.jsp").forward(request, response);
    }

    //执行开卡操作
    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int money = Integer.parseInt(request.getParameter("money"));
        int mid = Integer.parseInt(request.getParameter("mid"));
        String password = new ManagerDao().getManager(mid).getPassword();
        int sid = Integer.parseInt(request.getParameter("sid"));
        if(new StudentDao().getById(sid)!=null){
            //学号已经存在

            request.setAttribute("msg","学号已存在！");
            request.setAttribute("manager",new ManagerDao().getManager(mid));
            request.getRequestDispatcher("/addStudentAndCard.jsp").forward(request,response);
        }else if(!password.equals(request.getParameter("managerPassword"))){
            //密码验证不通过
            request.setAttribute("msg","管理员密码输入错误！");
            request.setAttribute("manager",new ManagerDao().getManager(mid));
            request.getRequestDispatcher("/addStudentAndCard.jsp").forward(request,response);
        }else{
             /*
             密码验证通过 开始开卡
                1.创建学生
                2.创建饭卡(带余额）
                3.开账单
             */
            //创建学生
            new StudentDao().studentAdd(
                    sid,
                    request.getParameter("name"),
                    request.getParameter("password"),
                    request.getParameter("sex"),
                    request.getParameter("dept"),
                    request.getParameter("tel")
            );
            //创建饭卡（带初始余额）
            new CardDao().cardAdd(
                    sid,
                    Integer.parseInt(request.getParameter("money"))
            );
            //拿到新卡号，写入账单
            int cid = new CardDao().getCid(sid);
            new BillDao().billAdd(
                    cid,
                    Integer.parseInt(request.getParameter("money"))
            );
            //跳转到管理到该学生页
            request.setAttribute("msg","开卡成功，卡号："+cid+"，学号："+sid);
            request.getRequestDispatcher("/ManagerServlet?m=searchStuAll&sid="+sid).forward(request,response);
        }
    }

    //准备饭卡充值，跳到饭卡页
    private void toAddCardMoney(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //根据cid获取饭卡、学生信息
        Card card = new CardDao().getCardByCid(Integer.parseInt(request.getParameter("cid")));
        Student student = new StudentDao().getById(card.getSid());

        request.setAttribute("card",card);
        request.setAttribute("student",student);
        request.getRequestDispatcher("/addCardMoney.jsp").forward(request,response);
    }
    //饭卡充值功能
    private void addCardMoney(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int addMoney = Integer.parseInt(request.getParameter("money"));//充值金额
        int mid = Integer.parseInt(request.getParameter("mid"));
        int cid = Integer.parseInt(request.getParameter("cid"));
        String password = new ManagerDao().getManager(mid).getPassword();
        if (!password.equals(request.getParameter("managerPassword"))) {
            //密码验证不通过,把饭卡和学生发送回去
            System.out.println("管理员密码错误");
            request.setAttribute("msg", "管理员密码输入错误！");
            request.setAttribute("card",new CardDao().getCardByCid(cid));
            request.setAttribute("student",new StudentDao().getById(new CardDao().getSid(cid)));
            request.getRequestDispatcher("/addCardMoney.jsp").forward(request, response);
        } else {
             /*
             密码验证通过 开始充值
                1.更新饭卡余额
                2.开账单
             */

            //更新饭卡余额
            new CardDao().cardUpdate(cid,addMoney);
            //写入账单
            new BillDao().billAdd(
                    cid,
                    Integer.parseInt(request.getParameter("money"))
            );
            //拿学号，用来转发到该学生页
            int sid = new CardDao().getSid(cid);
            //跳转到管理到该学生页
            request.setAttribute("msg", "充值成功，卡号：" + cid + "，充值金额：" + addMoney+"元");
            request.getRequestDispatcher("/ManagerServlet?m=searchStuAll&sid=" + sid).forward(request, response);
        }

    }
    //删除学生/饭卡功能
    private void delete (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
            销号 ：
            1.删除与该账号有关的账单，
            2.删除饭卡，
            3.删除学生
        */
        String msg = null;
        //获取两个主键
        int sid = Integer.parseInt(request.getParameter("sid"));
        int cid = Integer.parseInt(request.getParameter("cid"));
        //删除相关账单
        boolean deleteBills = new  BillDao().deleteBillByCid(cid);
        //删除饭卡
        boolean deleteCard = new CardDao().deleteCard(cid);
        //删除学生
        boolean deleteStudent = new StudentDao().deleteStudent(sid);
        if(deleteBills==true && deleteCard==true && deleteStudent==true){
            msg = "删除成功";
        }else{
            msg = "删除失败";
        }
        request.setAttribute("msg",msg);
        request.getRequestDispatcher("/managerView.jsp").forward(request,response);
    }
}


